package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController("admin/dish")
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "菜品相关接口")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    //菜品分页查询
    @ApiOperation(value = "分页查询菜品", notes = "分页查询菜品")
    @GetMapping("/page")
    public Result<PageResult> page(
            DishPageQueryDTO queryDTO
    ){
        log.info("菜品分页查询：{}",queryDTO);
        PageResult pageResult = dishService.page(queryDTO);
        return Result.success(pageResult);
    }

    //新增菜品
    @PostMapping
    @ApiOperation(value = "新增菜品", notes = "新增菜品")
    public Result save(@RequestBody DishDTO dishDTO){
        log.info("新增菜品：{}",dishDTO);
        dishService.saveWithFlavor(dishDTO);
        clearRedisCache("dish_*");
        return Result.success();
    }

    //修改菜品
    @PutMapping
    @ApiOperation(value = "修改菜品", notes = "修改菜品")
    public Result updata(
            @RequestBody DishDTO dishDTO
    ){
        log.info("修改菜品：{}",dishDTO);
        dishService.updata(dishDTO);
        //清楚redis缓存
//        String key = "dish_" + dishDTO.getCategoryId();
        clearRedisCache("dish_*");

        return Result.success();
    }

    //删除菜品
    @ApiOperation("删除菜品")
    @DeleteMapping
    public Result delete(@RequestParam List<Integer> ids){
        log.info("删除菜品：{}",ids);
        dishService.delete(ids);
        //清楚redis缓存
        clearRedisCache("dish_*");
        return Result.success();
    }
    //根据id查询菜品 做回显
    @ApiOperation(value = "根据id查询菜品", notes = "根据id查询菜品")
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable("id") Long id){
        log.info("查询菜品id：{}", id);
        DishVO dishVO = dishService.selectByidWithFlavor(id);

        return Result.success(dishVO);
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> list(Long categoryId){
        List<Dish> list = dishService.list(categoryId);
        return Result.success(list);
    }

    public  void  clearRedisCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
